package com.nf.health.app.datamain.activity;

import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.activity.manage_health.bean.SugarEvent;
import com.nf.health.app.activity.my.MyShopStoreActivity;
import com.nf.health.app.adapter.OnMyClickListener;
import com.nf.health.app.customview.HpBrokenLine;
import com.nf.health.app.customview.MenuPopupWindow;
import com.nf.health.app.customview.WheelView;
import com.nf.health.app.http.RequestProvider;
import com.nf.health.app.models.BloodSugarDataBean;
import com.nf.health.app.models.BluetoothDeviceAttr;
import com.nf.health.app.models.DeviceData;
import com.nf.health.app.service.BluetoothLeService;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.LogUtil;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.Util;
import com.nf.health.app.utils.ViewUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bluetools.ProtocolParser;

/**
 * Created by hepan on 2016/3/18.
 */
public class BloodSugarDataActivity extends BaseActivity {

    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        public static final String TAG = "mGattUpdateReceiver";

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                showToast("蓝牙连接");
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                showToast("蓝牙连接断开,请重试");
                hideLoading();
            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                byte[] data = intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);
                if (data == null) {
                    return;
                }
                LogUtil.e(TAG, ProtocolParser.binaryToHexString(data) + ">>>>" + data.length);
                try {
                    handleBloodSugarData(data);
                } catch (Exception e) {
                    LogUtil.exception(e);
                }
            }
        }
    };

    /**
     * 网络请求相关
     * httpFlag
     */
    protected RequestProvider provider;
    private static final String ADD_BLOOD_GLUCOSE_MANUALLY = "add_blood_glucose_manually"; //手动添加数据
    private static final String ADD_BLOOD_GLUCOSE_MECHANICAL = "add_blood_glucose_mechanical"; //机器测量添加数据
    private static final String REQUEST_BLOOD_SUGAR_DATA = "request_blood_sugar_data"; //请求血糖数据

    @Bind(R.id.rl_broken_line)
    LinearLayout rlBrokenLine;

    private String deviceType;

    @Bind(R.id.iv_background)
    ImageView ivBackground;
    @Bind(R.id.tv_blood_presure)
    TextView tvBloodPresure;
    @Bind(R.id.tv_date_desc)
    TextView tvDateDesc;
    @Bind(R.id.tv_sugar_data)
    TextView tvSugarData;
    @Bind(R.id.tv_history_data)
    TextView tvHistoryData;
    @Bind(R.id.btn_measure)
    Button btnMeasure;
    @Bind(R.id.titlebar_right_view)
    ImageView titlebarRightView;


    /**
     * 处理返回的数据
     *
     * @param data
     */
    private void handleBloodSugarData(byte[] data) {
        if (data.length == 8) {
            if (data[5] == (byte) 0xAA && data[6] == (byte) 0xBB) {
                //连接设备成功
            } else if (data[5] == (byte) 0xBB && data[6] == (byte) 0xBB) {
                //请滴血进行测量
            } else {
                if (data[6] == (byte) 0xBB) {
                    int time = data[5] & 0xFF;
                } else if (data[6] == (byte) 0x88) {
                    int count = 0;
                    for (int i = 0; i < data.length - 1; i++) {
                        count += (data[i] );
                    }
                    byte[] cks = ProtocolParser.intToByteArray(count);
                    if (cks[cks.length - 1] == data[7]) {
                        hideLoading();
                        float aa = (data[4] * 0x100 + (data[5]+256)%256) / 18f;
                        aa = (float) Math.round(aa * 10) / 10;
                        /**
                         * 测量时间和结果存储到sp,并上传到服务器
                         */
                        PreferenceHelper.putInt(PreferenceHelper.BLOOD_SUGAR_MEASURED_TIME, measured_time);
                        PreferenceHelper.putString(PreferenceHelper.BLOOD_SUGAR_MEASURED_VALUE, aa + "");
                        provider.requestAddDeviceGlucoseNew(Math.abs(aa)+"", "2", measured_time + "", ADD_BLOOD_GLUCOSE_MECHANICAL);
                        tvBloodPresure.setText(aa+"");
                    } else {
                    }
                }
            }
        }
    }

    //扫描间隔5s
    private static final long INTERVAL_TIME = 5 * 1000;

    // Device scan callback.
    private BluetoothAdapter.LeScanCallback mLeScanCallback;
    private BluetoothAdapter mBluetoothAdapter;
    // 蓝牙服务类
    private BluetoothLeService mBluetoothLeService;
    private Handler handler = new Handler();
    private List<BluetoothDevice> devices = new ArrayList<>();

    private Handler mHandler = new Handler();
    private ServiceConnection mServiceConnection;
    /**
     * 标记TAB
     */
    private int currentIndex = 0;
    /**
     * 标记是否追加数据
     */
    private boolean isAppend = false;
    private byte[] result = new byte[24 * 3];
    /**
     * 复制字节数组的长度
     */
    int length = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContent(R.layout.activity_blood_sugar_data);
        setTitleBar(R.layout.layout_common_header);
        ButterKnife.bind(this);

        deviceType = getIntent().getStringExtra("deviceType");

        if (provider == null) {
            provider = new RequestProvider(this);
        }

        initView();
        initListener();
        initBluetooth();
        /**
         * 请求血糖首页数据 1 1 代表第一页第一条
         */
        provider.requestBloodSugarDataNew("1", "1", REQUEST_BLOOD_SUGAR_DATA);
    }


    /**
     * 初始化蓝牙
     */
    private void initBluetooth() {
        // 检查当前手机是否支持blue 蓝牙,如果不支持退出程序
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            showToast("不支持蓝牙4.0通讯");
            finish();
            return;
        }
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            showToast("没有发现蓝牙模块");
            return;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            //蓝牙扫描后的回调
            mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
                @Override
                public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //过滤出血糖仪
                            if(device != null){
                                if(!TextUtils.isEmpty( device.getName())){
                                        if(device.getName().contains(BluetoothDeviceAttr.BLOOD_SUGAR_DEVICE_NAME)){
                                            if (!devices.contains(device)) {
                                                devices.add(device);
                                            }
                                        }
                                }
                            }
                            /*if (device != null && device.getName().contains(BluetoothDeviceAttr.BLOOD_SUGAR_DEVICE_NAME)) {
                                if (!devices.contains(device)) {
                                    devices.add(device);
                                }
                            }*/
                        }
                    });
                }
            };
        } else {
            showToast("设备蓝牙版本过低");
            finish();
            return;
        }
        bindLeService();
        if (!mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.enable();
        }
    }

    private void bindLeService() {
        mServiceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName,
                                           IBinder service) {
                mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
                if (!mBluetoothLeService.initialize()) {
                    new MaterialDialog.Builder(BloodSugarDataActivity.this)
                            .title("提示")
                            .content("蓝牙初始化服务失败了~")
                            .positiveText("确定")
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(MaterialDialog dialog, DialogAction which) {
                                    finish();
                                }
                            })
                            .show();
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                mBluetoothLeService = null;
            }
        };

        Intent bleService = new Intent(this, BluetoothLeService.class);
        bleService.putExtra("type", DeviceData.Type.BLOOD_SUGAR);
        bindService(bleService, mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    /**
     * 初始化监听器
     */
    private void initListener() {
        titlebarRightView.setOnClickListener(this);
        tvHistoryData.setOnClickListener(this);
        btnMeasure.setOnClickListener(this);
    }

    /**
     * 初始化view
     */
    private void initView() {
        //设置标题
        ViewUtil.setText(this, R.id.titlebar_title_tv, "血糖数据");
        titlebarRightView.setVisibility(View.VISIBLE);
        ViewUtil.setImageResoure(this, R.id.titlebar_right_view, R.drawable.ic_title_setting);
        ViewUtil.setText(this,R.id.tv_blood_presure,PreferenceHelper.getString(PreferenceHelper.BLOOD_SUGAR_MEASURED_VALUE,"血糖值"));
    }

    /**
     * 初始化绑定设备弹窗
     */
    private void showPop() {
        MenuPopupWindow pop = new MenuPopupWindow(this, PreferenceHelper.getString(PreferenceHelper.BLOOD_SUGAR_NAME, ""));
        pop.showAsDropDown(titlebarRightView);
        pop.setOnMenuItemClickListener(new OnMyClickListener() {
            @Override
            public void onClick(int position, String flag) {
                if (R.id.ll_bind_device == position) {
                    if (PreferenceHelper.getBoolean(PreferenceHelper.BLOOD_SUGAR_IS_BING, false)) {
                        //TODO 解绑操作
                        PreferenceHelper.putBoolean(PreferenceHelper.BLOOD_SUGAR_IS_BING, false);
                        PreferenceHelper.putString(PreferenceHelper.BLOOD_SUGAR_ADDRESS, "");
                        PreferenceHelper.putString(PreferenceHelper.BLOOD_SUGAR_NAME, "");
                        showToast("解绑成功");
                        mBluetoothLeService.close();
                    } else {
                        scanLeDevice(true);
                    }
                } else if (R.id.tv_manual_input == position) {
                    //TODO 手动输入
                    addDadaManually();
                } else  if (R.id.tv_loadl_input == position) {
                    ActivityUtils.showActivity(BloodSugarDataActivity.this,MyShopStoreActivity.class);
                }
            }
        });
    }

    /**
     * 血糖范围 glucose_range ,血糖时间 time_range
     * 测量时间 measured_time  默认午餐后 5
     * 测量值 glucose_value   默认6.0
     */
    private String[] glucose_range = new String[120];
    private String[] time_range = {"凌晨", "早餐前", "早餐后", "午餐前", "午餐后", "晚餐前", "晚餐后", "睡前"};
    private int measured_time = 5;
    private String glucose_value = "6.0";

    /**
     * 手动添加数据
     */
    private void addDadaManually() {
        //初始化血糖范围 2.0~9.9
        for (int i = 4; i < 16; i++) {
            for (int j = 0; j < 10; j++) {
                glucose_range[(i-4) * 10 + j] = i + 2 + "." + j;
            }
        }
        measured_time = 5;//默认午餐后
        glucose_value = "8.0";//默认6.0

        View outerView = LayoutInflater.from(this).inflate(R.layout.wheel_view_blood_sugar, null);
        WheelView wv_time = (WheelView) outerView.findViewById(R.id.wheel_view_measured_time);
        WheelView wv_value = (WheelView) outerView.findViewById(R.id.wheel_view_glucose_value);

        wv_time.setOffset(1);
        wv_time.setItems(Arrays.asList(time_range));
        wv_time.setSeletion(time_range.length / 2);
        wv_time.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                measured_time = selectedIndex;
            }
        });

        wv_value.setOffset(1);
        wv_value.setItems(Arrays.asList(glucose_range));
        wv_value.setSeletion(20);
        wv_value.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                glucose_value = item;
            }
        });
        new AlertDialog.Builder(this)
                .setTitle("请选择")
                .setView(outerView)
                .setNegativeButton("取消", null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        SugarEvent sugarEvent = new SugarEvent();
                        sugarEvent.setSugarData(glucose_value);
                        EventBus.getDefault().post(sugarEvent);
                        provider.requestAddDeviceGlucoseNew(glucose_value, "1", measured_time + "", ADD_BLOOD_GLUCOSE_MANUALLY);
                        PreferenceHelper.putString(PreferenceHelper.BLOOD_SUGAR_MEASURED_VALUE, glucose_value);
                        ViewUtil.setText(BloodSugarDataActivity.this,R.id.tv_blood_presure,glucose_value);
                    }
                })
                .show();
    }

    /**
     * 网络请求结果
     *
     * @param actionName 请求标记
     * @param object     返回值
     */
    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        if (ADD_BLOOD_GLUCOSE_MANUALLY.equals(actionName)) {
            showToast("手动添加成功");
            provider.requestBloodSugarDataNew("1", "1", REQUEST_BLOOD_SUGAR_DATA);
            provider.requestAddScore("10", "");//添加积分
        } else if (ADD_BLOOD_GLUCOSE_MECHANICAL.equals(actionName)) {
            showToast("数据已上传到云端");
            provider.requestAddScore("10", "");//添加积分
            ActivityUtils.showActivity(this, BloodSugarMeasuredResultActivity.class);
        } else if (REQUEST_BLOOD_SUGAR_DATA.equals(actionName)) {
            BloodSugarDataBean bean = (BloodSugarDataBean) object;
            if (bean != null) {
                //初始化折线图
                initBrokenLine(bean);
            }
        }
    }

    /**
     * 初始化折线图
     *
     * @param bean 血糖数据bean类
     */
    private void initBrokenLine(BloodSugarDataBean bean) {

        ArrayList<BloodSugarDataBean.DataBean.DeviceDataBean> datas = bean.data.deviceData;
        //若没有测过血糖,返回
        if (datas.size() == 0) {
            return;
        }
        BloodSugarDataBean.DataBean.DeviceDataBean data = datas.get(0);//首页只有一条数据
        String ss = tvBloodPresure.getText().toString();
        if(!TextUtils.isEmpty(ss) && ss.equals("血糖值")){
            ViewUtil.setText(this,R.id.tv_blood_presure,PreferenceHelper.getString(PreferenceHelper.BLOOD_SUGAR_MEASURED_VALUE,""+data.before_sleep));
        }
        rlBrokenLine.removeAllViews();
        ArrayList<String> xdata = new ArrayList<>(); //不知道有啥用 限制个数?
        for (int i = 0; i < 8; i++) {
            xdata.add(i * 1f + "");
        }
        ArrayList<Float> ydata = new ArrayList<>(); //设置纵轴数据
        ydata.add(data.before_dawn + 0f);
        ydata.add(data.before_glucose + 0f);
        ydata.add(data.after_glucose + 0f);
        ydata.add(data.before_lunch + 0f);
        ydata.add(data.after_lunch + 0f);
        ydata.add(data.before_dinner + 0f);
        ydata.add(data.after_dinner + 0f);
        ydata.add(data.before_sleep + 0f);
        rlBrokenLine.addView(new HpBrokenLine(this, xdata, ydata, 20f, 0f, 1, 10));
    }

    /**
     * 扫描蓝牙设备
     *
     * @param enable
     */
    private void scanLeDevice(final boolean enable) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            if (enable) {
                showLoading("查找设备中..");
                devices.clear();
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
                // Stops scanning after a pre-defined scan period.
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                            mBluetoothAdapter.stopLeScan(mLeScanCallback);
                            hideLoading();
                            showBluetoothNames();
                        }
                    }
                }, INTERVAL_TIME);
                mBluetoothAdapter.startLeScan(mLeScanCallback);
            } else {
                try {
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                } catch (Exception e) {
                }
            }
        }
    }


    private void showBluetoothNames() {
        if (devices.size() <= 0) {
           // new MaterialDialog.Builder(this).title("提示").content("没有发现血糖仪噢~").positiveText("确定").show();
            Util.showNotHasFountDeviced(BloodSugarDataActivity.this);
            return;
        }
        String[] deviceNames = new String[devices.size()];
        for (int i = 0; i < devices.size(); i++) {
            String address = devices.get(i).getAddress();
            deviceNames[i] = "血糖仪-" + address.replace(":", "");
        }
        //mLeScanCallback 将搜索结果添加到集合中
        if(!isFinishing()) {
            new MaterialDialog.Builder(this)
                    .title("血糖仪")
                    .items(deviceNames)
                    .itemsCallback(new MaterialDialog.ListCallback() {
                        @Override
                        public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
//                        mBluetoothLeService.connect(devices.get(which).getAddress());
                            PreferenceHelper.putBoolean(PreferenceHelper.BLOOD_SUGAR_IS_BING, true);
                            PreferenceHelper.putString(PreferenceHelper.BLOOD_SUGAR_NAME, "血糖仪计-" + devices.get(which).getAddress().replace(":", ""));
                            PreferenceHelper.putString(PreferenceHelper.BLOOD_SUGAR_ADDRESS, devices.get(which).getAddress());
                            dialog.dismiss();
                        }
                    })
                    .show();
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            //右边按钮的点击事件
            case R.id.titlebar_right_view:
                showPop();
                break;
            //历史数据tv点击
            case R.id.tv_history_data:
                ActivityUtils.showActivity(this, BloodSugarHistoryDataActivity.class);
                break;
            //测量按钮点击
            case R.id.btn_measure:
                if (TextUtils.isEmpty(PreferenceHelper.getString(PreferenceHelper.BLOOD_SUGAR_ADDRESS, ""))) {
                    showPop();
                }else{
                    //机器测量
                    measureDataByMeachine();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 机器测量
     */
    private void measureDataByMeachine() {
        measured_time = 5;//默认午餐后

        View outerView = LayoutInflater.from(this).inflate(R.layout.wheel_view_blood_sugar, null);
        WheelView wv_time = (WheelView) outerView.findViewById(R.id.wheel_view_measured_time);
        outerView.findViewById(R.id.ll_ww_tv).setVisibility(View.GONE);

        wv_time.setOffset(1);
        wv_time.setItems(Arrays.asList(time_range));
        wv_time.setSeletion(time_range.length / 2);
        wv_time.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                measured_time = selectedIndex;
            }
        });
        if(!isFinishing()) {
            new AlertDialog.Builder(this)
                    .setTitle("请选择时段")
                    .setView(outerView)
                    .setNegativeButton("取消", null)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //开始测量
                            if (!TextUtils.isEmpty(PreferenceHelper.getString(PreferenceHelper.BLOOD_SUGAR_ADDRESS, ""))) {
                                showLoading("测量中...");
                                mBluetoothLeService.connect(PreferenceHelper.getString(PreferenceHelper.BLOOD_SUGAR_ADDRESS, ""));
                            }
                        }
                    })
                    .show();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mGattUpdateReceiver, BluetoothLeService.makeGattUpdateIntentFilter());
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mGattUpdateReceiver != null) {
            unregisterReceiver(mGattUpdateReceiver);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mServiceConnection != null) {
            unbindService(mServiceConnection);
        }
        mBluetoothLeService.close();
        mBluetoothLeService = null;
    }
}
